<template>
  <el-container style="height: 100%; border: 1px solid #eee">
        <el-aside v-show="isShowAside" width="350px" style="margin-top:5px;background-color: rgb(238, 241, 246);">
          <el-input
            :disabled="isDisabled"
            style="width:350px"
            placeholder="请输入公司名"
            v-model="companyInfo.searchText"
            @change="getAllCompany(true)"
            clearable>
            <el-select :disabled="isDisabled" clearable style="width:80px" v-model="companyInfo.selectText" @change="getAllCompany(true)" slot="prepend" placeholder="请选择">
              <el-option label="上市" value="1"></el-option>
              <el-option label="未上市" value="0"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="getAllCompany(true)"></el-button>
          </el-input>
          <el-scrollbar style="width: 350px;" :style="{marginTop:'2px',height:bomHeight+'px'}" ref="treeScroll">
            <ul v-if="companyInfo.refreshLi" >
              <li @click="selectCompany(item)" class="company_li" :class="item.isActive===true? 'active':''" v-for="item in companyInfo.companyList">
                <i v-if="item.listedCompanies===1" class="el-icon-s-flag"></i>
                {{item.name}}
              </li>
            </ul>
          </el-scrollbar>

        </el-aside>

    <el-main>
      <el-card  :style="isShowAside? {position: 'absolute',top:'10px',left:'380px'}:{position: 'absolute',top:'20px',left:'0'}" style="z-index: 2000;width: 420px" :class="isShowAside? 'attrPlane':'showattrPlane'">
        <el-row>
          <i style="cursor:pointer;line-height: 44px;margin-right: 20px;float: left" :class="isShowAside? 'el-icon-d-arrow-left':'el-icon-d-arrow-right'" @click="showAside" plain></i>
          <div id="mysign">
            <el-popover

              v-for="(item,i) in currentNaoTu.colorOptions"
              placement="bottom"
              width="400"
              trigger="click">
              <el-form>
                <el-form-item :label="currentNaoTu.colorOptions[i].label">
                  <el-color-picker v-model="currentNaoTu.colorOptions[i].value"></el-color-picker>
                </el-form-item>
              </el-form>
              <el-button style="font-weight:bolder;color:rgba(0,0,0,0.5);" size="medium" :style="{background: currentNaoTu.colorOptions[i].value}" slot="reference">{{currentNaoTu.colorOptions[i].label}}</el-button>
            </el-popover>
          </div>
        </el-row>
        <el-form  v-show="isShowAside" >
          <el-form-item label="模板">
            <el-select  style="width:150px" @change="changeTemplate" v-model="currentNaoTu.template" clearable placeholder="请选择">
              <el-option
                v-for="item in templateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="主题色">
            <el-select  style="width:150px" @change="changeTheme" v-model="currentNaoTu.themeValue" clearable placeholder="请选择">
              <el-option
                v-for="item in themeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="层级">
            <el-input-number  v-model="currentNaoTu.level" @change="changeLevel" :min="1" :max="10" label="展开层级"></el-input-number>
          </el-form-item>
          <el-form-item label="缩放">
            <el-input-number v-model="currentNaoTu.size" @change="changeSize" :min="1" :max="100" label="描述文字"></el-input-number>
          </el-form-item>
         <el-form-item label="下载">
           <el-button  @click="exportTo('png','png')">图片</el-button>
           <el-button @click="exportTo('svg','svg')">svg</el-button>
         </el-form-item>

         <el-form-item label="操作">
           <el-button type="primary" plain @click="saveStorage">保存</el-button>
         </el-form-item>
        </el-form>
      </el-card >
      <div :style="{width:'calc(100%)'}" v-if="companyInfo.refreshLi" id="minder-container"></div>
      <el-card v-if="currentCompany.isShowInfo" style="width:500px;position: absolute;top:0;right:0">
        <i style="cursor: pointer" class="el-icon-close" @click="currentCompany.isShowInfo=false"></i>
        <br/>
        <el-form size="mini" label-width="80px">
          <el-form-item label="名称">
            {{currentCompany.currentPolicy.text}}
          </el-form-item>
          <el-form-item label="链接">
            <a :href="currentCompany.currentPolicy.href">{{currentCompany.currentPolicy.href}}</a>
          </el-form-item>
          <el-form-item label="等级">
            <el-tag v-if="currentCompany.currentPolicy.grade==='1'" type="danger">国家</el-tag>
            <el-tag v-if="currentCompany.currentPolicy.grade==='2'" type="primary">省</el-tag>
            <el-tag v-if="currentCompany.currentPolicy.grade==='3'" type="success">市</el-tag>
            <el-tag v-if="currentCompany.currentPolicy.grade==='4'" type="info">区县</el-tag>
          </el-form-item>
          <el-form-item label="申报条件">
            <el-row v-for="(item,index) in currentCompany.declarationSubsidy.shenbao">
              <el-link type="primary">{{index+1}}</el-link>{{item.cdName}}
            </el-row>
          </el-form-item>
          <el-form-item label="补助条件">
            <el-row v-for="(item,index) in currentCompany.declarationSubsidy.buhuan">
              <el-link type="primary">{{ index+1 }}</el-link>{{item.cdName}}
            </el-row>
          </el-form-item>
        </el-form>
      </el-card>
       </el-main>
  </el-container>

</template>

<script>
import axios from "axios";
import html2canvas from 'html2canvas'
import 'vue-kityminder-editor/lib/kityMinder.css'
import kityMinder from 'vue-kityminder-editor'


export default {
  name: "McSwdtBaidu",
  components:{kityMinder},
  props:{
    datamanager: {
      type: String, default: ``
    },
  },
  data() {
    return {
      magicalCoderUrl:"https://unicoder.zippro.cn/youyaboot-admin/magical_lowcode/openapi/fc706fc3d37242f2a9ec0925923cee37/",

      isDisabled:false,
      minder:null,   //操作脑图
      isShowAside:false,  //显示侧边栏
      bomHeight:window.innerHeight-80,

      companyInfo:{
        pageIndex:1,
        limitNum:30,
        // searchText:"佳吉化纤有限公司",    //文本框内
        searchText:"",    //文本框内
        selectText:"",    //选择框
        companyList:[],
        refreshLi:true,
      },
      execOne:true,
      bureauList:[],  //局办
      allPolicy:[],   //所有政策

      currentCompany:{
        ads:{},          //公司所在省市区信息
        company:"",
        isShowInfo:false,  //显示详情
        declarationSubsidy:{
          shenbao:[],         //申报条件
          buhuan:[],          //补助条件
        },  //
        currentPolicy:{},  //当前政策,显示在右上角
        allPolicy:[],      //符合公司地区的所有政策
        isHavePolicy:[],    //已获取福利
        applyingPolicy:[],  //正在申请的福利
        policyFuture:{
          policy1:[],
          policy2:[],
          policy3:[],

        }, //未来3年推荐政策
        importJson: {data:{'text': '公司名', 'priority': 1, 'id': 3 },children:[]},
      },
      themeOptions:[
        {label:"红色",value:"fresh-red"},
        {label:"紧缩红色",value:"fresh-red-compat"},
        {label:"棕色",value:"fresh-soil"},
        {label:"紧缩棕色",value:"fresh-soil-compat"},
        {label:"绿色",value:"fresh-green"},
        {label:"紧缩绿色",value:"fresh-green-compat"},
        {label:"蓝色",value:"fresh-blue"},
        {label:"紧缩蓝色",value:"fresh-blue-compat"},
        {label:"紫色",value:"fresh-purple"},
        {label:"紧缩紫色",value:"fresh-purple-compat"},
        {label:"粉色",value:"fresh-pink"},
        {label:"紧缩粉色",value:"fresh-pink-compat"}
      ],
      templateOptions:[
        {label:"default",value:"default"},
        {label:"filetree",value:"filetree"},
        {label:"fish-bone",value:"fish-bone"},
        {label:"right",value:"right"},
        {label:"structure",value:"structure"},
        {label:"tianpan",value:"tianpan"}
      ],
      currentNaoTu:{
        template:"default",
        size:80,
        themeValue:"fresh-blue",    //主题色
        level:4,                     //展开层级
        colorOptions:[
          {label:"已获",value:"rgba(0,122,0,0.4)"},
          {label:"申报",value:"rgba(255,0,0,0.4)"},
          {label:"1年",value:"rgba(128,0,128,0.1)"},
          {label:"2年",value:"rgba(135,206,235,0.4)"},
          {label:"3年",value:"rgba(255,255,0,0.4)"}
        ],
      },
    };
  },
  mounted() {
    // this.magicalCoderUrl = JSON.parse(this.datamanager).magicalCoderUrl
    // 获取当前页面的 URL
    var url = new URL(window.location.href);
// 通过 URLSearchParams 获取参数
    var params = new URLSearchParams(url.search);
// 获取特定参数的值
    var plant = params.get('plant'); // 返回 "John"

    if(plant==='' || plant===null || plant===undefined){
      this.isDisabled = false
    }else{
      this.companyInfo.searchText = plant
      this.isDisabled = true
    }

    this.initSwdt()
    this.getAllCompany()
    this.getAllBureau()
    this.treeScroll()

    },
  methods: {

    /**保存数据**/
    saveStorage(){
      localStorage.setItem("swdtData",JSON.stringify(this.currentNaoTu))
    },
    /**监听滚动事件**/
    treeScroll(){
      let scrollbarEl = this.$refs.treeScroll.wrap;
      scrollbarEl.onscroll = () => {
        const content = scrollbarEl.scrollHeight; // 获取 el-scrollbar 的内容容器
        const atBottom = (scrollbarEl.scrollTop + scrollbarEl.clientHeight)+1 >= content;
        if (atBottom) {
          this.debounce(this.nextLoad)
        }
      };
    },
    /**防抖函数**/
    debounce(func) {
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer)
      }
      // 设置一个 500ms 的计时器来延迟响应传递的函数
      this.debounceTimer = setTimeout(() => {
        func()
        this.debounceTimer = null
      }, 300)
    },
    /**初始加载tree bom信息**/
    clickLoad(){
      this.companyInfo.companyList=[]
      this.companyInfo.pageIndex=1
      this.getAllCompany()
    },
    /**加载下一页**/
    nextLoad(){
      // 已经滚动到底部，执行你的操作
      if(this.execOne){
        this.execOne=false
        console.log('已经滚动到底部');
        this.getAllCompany()
      }
    },
    /**获取申报、补助条件**/
    getDeclarationSubsidy(item){
      if(this.currentCompany.company===""){
        this.$message.warning("请选择公司")
        return
      }
      return new Promise(resolve => {
        axios({
          method: "post",
          url: this.magicalCoderUrl+"policy-declaration-subsidy",
          data:{
            'policy_id': item.id,
            'area_id': this.currentCompany.company.areaId
          }
        }).then((info) => {
          if(info.data.data.length>0){
            this.currentCompany.declarationSubsidy={
              shenbao:[],
              buhuan:[]
            }
            info.data.data.forEach(item=>{
              if(item.cdType==="补助条件"){
                this.currentCompany.declarationSubsidy.shenbao.push(item)
              }else if(item.cdType==="申报条件"){
                this.currentCompany.declarationSubsidy.buhuan.push(item)
              }
            })
          }

          resolve(1)
        })
      })
    },
    initNaoTu(){
      this.changeTheme()
      this.changeLevel()
      this.changeSize(this.currentNaoTu.size)
      this.changeTemplate()
    },
    initSwdt(){
      // this.minder=this.$refs.swdt.KMEditor.minder
      this.minder= new kityminder.Minder({
        renderTo: '#minder-container',
      });

      this.minder.on('click',(e)=>{
        let selectNode = e.minder._selectedNodes
        console.log(selectNode)

        if(selectNode.length===1){
          this.currentCompany.isShowInfo=true
          this.currentCompany.currentPolicy=selectNode[0].data
          this.getDeclarationSubsidy(selectNode[0].data)
        }
      })
      let itemInfo={
        id:99999,
        name:"全部公司"
      }
      Promise.all([
        this.getAllPolicy(itemInfo)
      ]).then(()=>{

        let swdtData = localStorage.getItem("swdtData")
        if(swdtData){
          try {
            this.currentNaoTu = JSON.parse(swdtData)
          }catch (e) {
            console.log("localStorage.getItem(swdtData)报错")
          }
        }
        this.initNaoTu()
      })

    },
    /**显示隐藏**/
    showAside(){
      this.isShowAside=!this.isShowAside
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(',');
      //注意base64的最后面中括号和引号是不转译的
      var _arr = arr[1].substring(0, arr[1].length - 2);
      var mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(_arr),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime
      });
    },
    async exportTo(exportType,realType) {
      console.log("exportType",exportType)
      this.minder.exportData(exportType).then( async (content) => {
        console.log("content",content)
        // let fileName = ""
        // var blob = new Blob();
        // switch (exportType) {
        //   case 'png':
        //     fileName = "DEFAULT.png";
        //     blob = this.dataURLtoBlob(content); //将base64编码转换为blob对象
        //
        //     break;
        //   case 'svg':
        //     fileName = "DEFAULT.svg";
        //     blob = new Blob([content], {type: 'image/svg+xml'});
        //
        //     break;
        // }
        // console.log("blob",blob)
        // var a = document.createElement("a"); //建立标签，模拟点击下载
        // a.download = fileName
        // a.href = URL.createObjectURL(blob);
        // a.click();
      });

      //方法一
      // var node = document.getElementById(id);
      // domtoimage.toSvg(node, { bgcolor: '#fff',width:'100%',height:'120vh'}).then(dataUrl => {
      //   const a = document.createElement("a");
      //   a.href = dataUrl;
      //   a.download = "DEFAULT.svg";
      //   a.click();
      // }).catch(error => {
      // });

      //方法二
      // let dom = document.getElementById(id)
      // const wMap = new WeakMap();
      // const imgObj = {
      //   width: 0,
      //   height: 0,
      // };
      // const canvas = await html2canvas(dom);
      // const imgUrl = canvas.toDataURL("image/jpeg", 1.0);
      // imgObj.width = canvas.width;
      // imgObj.height = canvas.height;
      // wMap.set(dom, imgUrl);
      //
      // const image = document.createElement("img");
      // const dataUrl = wMap.get(dom);
      // image.src = b64Data;
      // document.body.appendChild(image);
      // const a = document.createElement("a");
      // a.href = dataUrl;
      // a.download = "DEFAULT.svg";
      // a.click();
    },
    /**导出pdf**/
    async exportToPDF(id) {

      //方法二
      let dom = document.getElementById(id)
      const wMap = new WeakMap();
      const imgObj = {
        width: 0,
        height: 0,
      };
      const canvas = await html2canvas(dom);
      const imgUrl = canvas.toDataURL("image/jpeg", 1.0);
      imgObj.width = canvas.width;
      imgObj.height = canvas.height;
      wMap.set(dom, imgUrl);



      // wMap.has(dom) ? null : await init(dom);
      let pdfName = "default.pdf"
      const domWidth = imgObj.width;
      const domHeight = imgObj.height;
      const b64Data = wMap.get(dom);
      const pageHeight = (domWidth / 592.28) * 841.89;
      // 未生成pdf的html页面高度
      let leftHeight = domHeight;
      // 页面偏移
      let position = 0;
      // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
      const imgWidth = 595.28;
      const imgHeight = (595.28 / domWidth) * domHeight;
      const pdf = new JsPdf("", "pt", "a4");

      // 有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
      // 当内容未超过pdf一页显示的范围，无需分页
      if (leftHeight < pageHeight) {
        // 在pdf.addImage(pageData, 'JPEG', 左，上，宽度，高度)设置在pdf中显示；
        pdf.addImage(b64Data, "JPEG", 0, 0, imgWidth, imgHeight);
        // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight);
      } else {
        // 分页
        while (leftHeight > 0) {
          pdf.addImage(b64Data, "JPEG", 0, position, imgWidth, imgHeight);
          leftHeight -= pageHeight;
          position -= 841.89;
          // 避免添加空白页
          if (leftHeight > 0) {
            pdf.addPage();
          }
        }
      }
      pdf.save(pdfName);

    },
    /**刷新公司列表**/
    refreshCompanyList(){
      this.companyInfo.refreshLi=false
      this.$nextTick(()=>{
        this.companyInfo.refreshLi=true
      })
    },
    /**刷新政策脑图**/
    refreshSwdt(){
      this.$refs.swdt.$forceUpdate()
    },
    /**获取所有公司**/
    getAllCompany(pushOrReplace){
      this.execOne=true
      if(pushOrReplace){
        this.companyInfo.pageIndex=1
      }
      axios({
        method: "post",
        url: this.magicalCoderUrl+"policy-get-plant?page="+this.companyInfo.pageIndex+"&limit="+this.companyInfo.limitNum,
        data:{
          cname:this.companyInfo.searchText===""? "":this.companyInfo.searchText,
          isList:this.companyInfo.selectText===""? "":this.companyInfo.selectText
        }
      }).then((info) => {
        this.$refs.treeScroll.scrollTop=0
        if(this.companyInfo.companyList.length>0){
          this.companyInfo.companyList.push(...info.data.data)
        }else{
          this.companyInfo.companyList=info.data.data
        }
        if(pushOrReplace){
          this.companyInfo.companyList=info.data.data
        }
        this.companyInfo.pageIndex+=1
        if(this.isDisabled){
          this.selectCompany(this.companyInfo.companyList[0])
        }
      })
    },
    clearBackground(){
      return new Promise(resolve => {
        this.minder._selectedNodes=[]
        this.minder._root.getChildren()[0].children.forEach(item=>{
          item.children.forEach(temp=>{
            this.minder._selectedNodes.push(temp)
          })
        })

        this.changeNodeBackgroundColor("")
        resolve(1)
      })
    },
    /**
     * 选择公司
     * **/
    async selectCompany(item) {
      this.currentCompany.company=item
      this.companyInfo.companyList.forEach(temp => {
        temp.isActive = temp.id === item.id;
      })
      Promise.all([
        this.getPolicyAnalysis(item)
      ]).then(() => {
        this.getAllPolicy(item)
      })
    },
    getPolicyAnalysis(item){
      return new Promise(resolve => {
        axios({
          method: "post",
          url: this.magicalCoderUrl+"policy-analysis-get",
          data:{
            'plant_id': item.id
          }
        }).then((info) => {
          let policyList=info.data.data
          this.currentCompany.isHavePolicy = []
          this.currentCompany.applyingPolicy= []
          this.currentCompany.policyFuture = {
            policy1: [],
            policy2: [],
            policy3: [],
          }

          if(policyList.length>0){
            policyList.forEach(temp=>{
             if(parseInt(temp.typeIndex)===1 && !this.currentCompany.isHavePolicy.some(item=> parseInt(item)===parseInt(temp.policyId))){
                this.currentCompany.isHavePolicy.push(parseInt(temp.policyId))
              }
              if(parseInt(temp.typeIndex)===2 && !this.currentCompany.applyingPolicy.some(item=>parseInt(item)===parseInt(temp.policyId))){
                this.currentCompany.applyingPolicy.push(parseInt(temp.policyId))
              }
              if(parseInt(temp.typeIndex)===3 && !this.currentCompany.policyFuture.policy1.some(item=>parseInt(item)===parseInt(temp.policyId))){
                this.currentCompany.policyFuture.policy1.push(parseInt(temp.policyId))
              }
              if(parseInt(temp.typeIndex)===4 && !this.currentCompany.policyFuture.policy2.some(item=>parseInt(item)===parseInt(temp.policyId))){
                this.currentCompany.policyFuture.policy2.push(parseInt(temp.policyId))
              }
              if(parseInt(temp.typeIndex)===5 && !this.currentCompany.policyFuture.policy3.some(item=>parseInt(item)===parseInt(temp.policyId))){
                this.currentCompany.policyFuture.policy3.push(parseInt(temp.policyId))
              }
            })

          }
          resolve(1)
        })
      })
    },
    /**获取所有局办**/
    getAllBureau(item) {
      return new Promise(resolve => {
        axios({
          method: "post",
          url: this.magicalCoderUrl + "policy-get-bureau",
          data: {}
        }).then((info) => {
          this.bureauList = info.data.data
        })
      })
    },
    /**获取所有政策**/
    getAllPolicy(item){
      return new Promise(resolve => {
        axios({
          method: "post",
          url: this.magicalCoderUrl+"policy-plant-mind-map",
          data:{
            plant_id:item.id,
            area_id:item.areaId
          }
        }).then((info) => {
          this.allPolicy = []
          let allPolicy = info.data.data

          allPolicy.forEach(item=>{
            if(item.effective===1 && item.isKey===1){
              this.allPolicy.push(item)
            }else if(this.currentCompany.isHavePolicy.some(temp=>parseInt(temp)===parseInt(item.value))){
              this.allPolicy.push(item)
              this.findParent(item,allPolicy)
            }else if(item.effective===1 && this.currentCompany.applyingPolicy.some(temp=>parseInt(temp)===parseInt(item.value))){
              this.allPolicy.push(item)
              this.findParent(item,allPolicy)
            }else if(item.effective===1 && this.currentCompany.policyFuture.policy1.some(temp=>parseInt(temp)===parseInt(item.value))){
              this.allPolicy.push(item)
              this.findParent(item,allPolicy)
            }else if(item.effective===1 && this.currentCompany.policyFuture.policy2.some(temp=>parseInt(temp)===parseInt(item.value))){
              this.allPolicy.push(item)
              this.findParent(item,allPolicy)
            }else if(item.effective===1 && this.currentCompany.policyFuture.policy3.some(temp=>parseInt(temp)===parseInt(item.value))){
              this.allPolicy.push(item)
              this.findParent(item,allPolicy)
            }
          })
          this.createSWDT(item,this.allPolicy)
          resolve(1)
        })
      })
    },
    findParent(item,allPolicy){
      if(item.parentId === 0){
        return
      }
      let policyId = item.parentId
      let curPolicy = allPolicy.find(item=>item.value === policyId)
      if(curPolicy){
        let isHave = this.allPolicy.find(item=>item.value === curPolicy.value)
        if(!isHave){
          this.allPolicy.push(curPolicy)
        }
        if(curPolicy.parentId!==0){
          this.findParent(curPolicy,allPolicy)
        }
      }

    },
    async createSWDT(company, allPolicy) {
      let noHeadPolicy = this.generateOptions(allPolicy)
      let brueaus = JSON.parse(JSON.stringify(this.bureauList))
      brueaus.forEach(temp => {
        temp.data = {
          text: temp.bureau,
          id: 99999 + temp.id
        }
        temp.children = []
      })
      noHeadPolicy.forEach(item => {
        let bureau = brueaus.find(temp => parseInt(temp.id) === parseInt(item.data.bureauId))

        if (bureau && bureau.children) {
          bureau.children.push(item)
        }
      })
      // 使用方法：
// 假设有一个id为"my-dom-element"的DOM元素
      var imageUrl = await this.domToImage('mysign');
      // console.log("img",imageUrl)

// 此时imageUrl就是DOM元素转换成的图片的base64编码URL
//       console.log(imageUrl);
      this.currentCompany.importJson = {
        'data': {
          'id': company.id,
          'text': company.name,
          'image': imageUrl,
          'imageSize': {width: 350, height: 85},
          'imageTitle': ''
        },
        'children': brueaus
      }
      // console.log(this.minder)
      this.minder.importJson(this.currentCompany.importJson)
      this.initNaoTu()
    },
    /**
     * dom转图片
     * @param domElement
     * @returns {string}
     */
    async domToImage(domElement) {
      let dom = document.getElementById(domElement)
      // const wMap = new WeakMap();
      const imgObj = {
        width: 0,
        height: 0,
      };
      const canvas = await html2canvas(dom);
      const imgUrl = canvas.toDataURL("image/jpeg", 1.0);
      imgObj.width = canvas.width;
      imgObj.height = 75;
      console.log(imgUrl)
      return imgUrl;
    },
    // 开始递归方法
    generateOptions(params) {
      var result = []
      for (const param of params) {
        if (param.parentId ===0 ) { // 判断是否为顶层节点
          let pLabel = ""
          if(param.grade==="1"){
            pLabel = "[国家]"+param.lable
          }else {
            pLabel = `[${param.gradeInfo}]`+param.lable
          }
          var parData = { text:pLabel+param.value, hyperlink:param.href, id:param.value,bureauId:param.bureau,grade:param.grade,priority:param.priority}

          parData.priority = param.priority

          //已获的政策
          if(this.currentCompany.isHavePolicy.includes(param.value)){
            parData.background = this.currentNaoTu.colorOptions[0].value
          }
          //正在申报的政策
          if(this.currentCompany.applyingPolicy.includes(param.value)){
            parData.background = this.currentNaoTu.colorOptions[1].value
          }
          if(this.currentCompany.policyFuture.policy1 && this.currentCompany.policyFuture.policy1.includes(param.value)){
            parData.background = this.currentNaoTu.colorOptions[2].value
          }
          if(this.currentCompany.policyFuture.policy2 && this.currentCompany.policyFuture.policy2.includes(param.value)){
            parData.background = this.currentNaoTu.colorOptions[3].value
          }
          if(this.currentCompany.policyFuture.policy3 && this.currentCompany.policyFuture.policy3.includes(param.value)){
            parData.background = this.currentNaoTu.colorOptions[4].value
          }
          var parent = {
            'value': param.value,
            'label': pLabel,
            'data': parData
          }
          parent.children = this.getchilds(param.value, params) // 获取子节点
          result.push(parent)
        }
      }
      return result
    },
    // 子循环
    getchilds(value, array) {
      const childs = []
      for (const arr of array) { // 循环获取子节点
        if (arr.parentId === value) {
          let pLabel = ""
          if(arr.grade==="1"){
            pLabel = "[国家]"+arr.lable
          }else {
            pLabel = `[${arr.gradeInfo}]`+arr.lable
          }
          //   if(arr.grade==="2"){
          //   pLabel = "[省]"+arr.lable
          // }else if(arr.grade==="3"){
          //   pLabel = "[市]"+arr.lable
          // }else if(arr.grade==="4"){
          //   pLabel = "[区县]"+arr.lable
          // }
          var cldData = { text:pLabel+arr.value, hyperlink:arr.href, id:arr.value,bureauId:arr.bureau,grade:arr.grade,priority:arr.priority}

          cldData.priority = arr.priority
          //已获的政策
          if(this.currentCompany.isHavePolicy.includes(arr.value)){
            cldData.background = this.currentNaoTu.colorOptions[0].value
          }
          //正在申报的政策
          if(this.currentCompany.applyingPolicy.includes(arr.value)){
            cldData.background = this.currentNaoTu.colorOptions[1].value
          }
          if(this.currentCompany.policyFuture.policy1 && this.currentCompany.policyFuture.policy1.includes(arr.value)){
            cldData.background = this.currentNaoTu.colorOptions[2].value
          }
          if(this.currentCompany.policyFuture.policy2 && this.currentCompany.policyFuture.policy2.includes(arr.value)){
            cldData.background = this.currentNaoTu.colorOptions[3].value
          }
          if(this.currentCompany.policyFuture.policy3 && this.currentCompany.policyFuture.policy3.includes(arr.value)){
            cldData.background = this.currentNaoTu.colorOptions[4].value
          }
          childs.push({
            'value': arr.value,
            'label': arr.pLabel,
            'data': cldData
          })
        }
      }
      for (const child of childs) { // 获取子节点的子节点
        const childscopy = this.getchilds(child.value, array) // 递归获取子节点
        if (childscopy.length > 0) {
          child.children = childscopy
        }
      }
      return childs
    },
    minderHandle (val) {
    },
    /**移动位置**/
    changePos(focusNode){
      this.minder._commands.move.execute( this.minder,'left', 1000);
    },
    /**切换模板**/
    changeTemplate(){
      this.minder._commands.template.execute( this.minder,this.currentNaoTu.template);
    },
    /**切换主题**/
    changeTheme(){
      this.minder._commands.theme.execute( this.minder,this.currentNaoTu.themeValue);
    },
    /**切换展开层级**/
    changeLevel(){
      this.minder._commands.expandtolevel.execute( this.minder,this.currentNaoTu.level);
    },
    /**添加备注信息**/
    changeNote(item) {
      this.minder._commands.note.execute( this.minder,item);
    },
    /**设置优先级**/
    changePriority(item) {
      this.minder._commands.priority.execute( this.minder,item);
    },
    /**选中节点修改背景颜色**/
    changeNodeBackgroundColor(colorText) {
      this.minder._commands.background.execute( this.minder,colorText);
    },
    /**选中节点添加超链接**/
    addLink(linkText){
      this.minder._commands.hyperlink.execute( this.minder,linkText);
    },
    /**缩放**/
    changeSize(size){
      this.minder._commands.zoom.execute( this.minder,size);
    },
  }
}
</script>

<style scoped>
@import "./swdtFile/local-kitymind/bower_components/bootstrap/dist/css/bootstrap.css";
@import "./swdtFile/local-kitymind/bower_components/codemirror/lib/codemirror.css";
@import "./swdtFile/local-kitymind/bower_components/hotbox/hotbox.css";
@import "./swdtFile/local-kitymind/bower_components/kityminder-core/dist/kityminder.core.css";
@import "./swdtFile/local-kitymind/bower_components/color-picker/dist/color-picker.min.css";

.company_li {
  background: #fff;
  width: 100%;
  height: 45px;
  padding:10px 20px;
}
.company_li:hover{
  cursor: pointer;
  background: rgba(0,0,0,0.1);
}
.active{
  background: rgba(0,0,0,0.1);
}
/*.attrPlane{*/
/*  position:absolute;left:300px;top:0;height:100px;width:100%;z-index: 999;*/
/*}*/
/*.showattrPlane{*/
/*  position:absolute;left:0;top:0;height:100px;width:100%;z-index: 999;*/
/*}*/
/*.toolGroup{*/
/*  width: 250px;*/
/*  margin-right:20px*/
/*}*/
</style>
